//
//  AmusementViewController.m
//  XiangMuB
//
//  Created by 999999999999 on 16/8/16.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "AmusementViewController.h"
#import "UIView+BSFrame.h"
#import "Content.h"
#import "CycleView.h"
#import "LMJNetWorkRequestManager.h"
#import "URL_HeaderDefine.h"
#import "AmusementModel.h"
#import "AmusementViewCell.h"
#import "ThreePhotoTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "WebViewController.h"
#import <MJRefresh.h>
@interface AmusementViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,assign) NSInteger time;
//轮播图属性
@property (nonatomic,strong)CycleView *cycleView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation AmusementViewController

-(void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}
-(NSMutableArray *)dataArray {
    if ( _dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
        //        self.start = @"0";
    }
    return _dataArray;
}

-(UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStyleGrouped)];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.time = 0 ;
    [self setUpTable];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    //创建头部轮播图
    self.cycleView = [[CycleView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250) interVal:60];
    self.cycleView.imgNameArray = [@[@"3.jpeg"] mutableCopy];
    
    //吧轮播图赋值tableHeaderView
    self.tableView.tableHeaderView = _cycleView;
    //点击时会触发的代码
    [self.cycleView addTapBlock:^(NSInteger index) {
        NSLog(@"当前点击第%ld页",(long)index);         //点击时没反应是因为没有打开交互
    }];
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:@"AmusementViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
#pragma mark 注册第二个cell

    [self.tableView registerNib:[UINib nibWithNibName:@"ThreePhotoTableViewCell" bundle:nil] forCellReuseIdentifier:@"threeCell"];
    
}

//#pragma mark----初始化tableview
-(void)setUpTable{
    //  设置内边距
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top =TitlesViewY +TitlesViewH;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    //设置滚动条内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    [self setUpRefresh];
}
#pragma mark----刷新数据
-(void)setUpRefresh{
    //下拉刷新,在主线程结束刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
    //    根据拖拽比例自动改变透明度
    self.tableView.header.autoChangeAlpha = YES;
    //进入页面自动刷新
    [self.tableView.mj_header beginRefreshing];
    //下拉刷新,加载更多数据
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    
}

#pragma mark --第一次获取数据
- (void)loadNewTopic {
    
    [self.tableView.mj_footer endRefreshing];
    self.time = 0;
    __weak typeof(self)weakSelf = self;
    NSString *urlStr = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/T1348648517839/%ld-20.html", self.time];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLSession *session = [NSURLSession sharedSession];//系统提供全局的单利
    
    //3创建task任务执行对象
    NSURLSessionTask *sessionTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error == nil) {
            [weakSelf.dataArray removeAllObjects];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            //        NSLog(@"%@",dic);
            for (NSDictionary *dic2  in dic[@"T1348648517839"]) {
                //            NSLog(@"%@",dic2);
                
                AmusementModel *model = [[AmusementModel alloc]init];
                [model setValuesForKeysWithDictionary:dic2];
                [weakSelf.dataArray addObject:model];
            }
            //        NSLog(@"%@",self.dataArray);
#pragma mark----刷新视图
            dispatch_async(dispatch_get_main_queue(), ^{
                //结束刷新
                [weakSelf.tableView.mj_header endRefreshing];
                weakSelf.time += 20;
                [weakSelf.tableView reloadData];
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                //结束刷新
                [weakSelf.tableView.mj_header endRefreshing];
            });
        }
    }];
    //执行
    [sessionTask resume];
}

#pragma mark ---获取更多
- (void)loadMoreTopic {
    [self.tableView.mj_header endRefreshing];
    __weak typeof(self)weakSelf = self;
    NSString *urlStr = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/T1348648517839/%ld-20.html", self.time];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLSession *session = [NSURLSession sharedSession];//系统提供全局的单利
    
    //3创建task任务执行对象
    NSURLSessionTask *sessionTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error == nil) {
            self.time += 20;
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            //        NSLog(@"%@",dic);
            for (NSDictionary *dic2  in dic[@"T1348648517839"]) {
                //            NSLog(@"%@",dic2);
                
                AmusementModel *model = [[AmusementModel alloc]init];
                [model setValuesForKeysWithDictionary:dic2];
                [weakSelf.dataArray addObject:model];
            }
            //        NSLog(@"%@",self.dataArray);
#pragma mark----刷新视图
            dispatch_async(dispatch_get_main_queue(), ^{
                //结束刷新
                [weakSelf.tableView.mj_footer endRefreshing];
                weakSelf.time += 20;
                [weakSelf.tableView reloadData];
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                //结束刷新
                [weakSelf.tableView.mj_footer endRefreshing];
            });
        }
    }];
    //执行
    [sessionTask resume];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AmusementModel *model = self.dataArray[indexPath.row];
    if (model.imgextra == nil) {
#warning 只有一个图片的cell
        AmusementViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        if (cell == nil) {
            cell = [[AmusementViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
        }
        AmusementModel *model = self.dataArray[indexPath.row];
        
        cell.model = model;
        return cell;
    } else {
#warning 有三个图片的cell
        ThreePhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"threeCell"];
        
        if (cell == nil) {
            cell = [[ThreePhotoTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"threeCell"];
        }
        AmusementModel *model = self.dataArray[indexPath.row];
        cell.model = model;
        return cell;
    }
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    AmusementModel *model = self.dataArray[indexPath.row];
    if (model.imgextra == nil) {
#warning 只有一个图片的cell
        AmusementViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        AmusementModel *model = self.dataArray[indexPath.row];
        cell.model = model;
        return 118;
    } else {
        ThreePhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"threeCell"];
        AmusementModel *model = self.dataArray[indexPath.row];
        cell.model = model;
        return 148;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WebViewController *webVC = [[WebViewController alloc]init];
    webVC.urlStr = [self.dataArray[indexPath.row] url_3w];
    [self.navigationController pushViewController:webVC animated:YES];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
